import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/index'
//import LoginPage from '../views/login/LoginPage.vue'

// createRouter 创建路由实例
// 配置 history模式
// 1. history模式： createWebHistory      地址栏不带#
// 2. hash模式：    createWebHashHistory  地址栏带 #
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { path: '/login', component: () => import('@/views/login/LoginPage.vue') }, // 一级路由，登录页
    {
      path: '/',
      component: () => import('@/views/layout/LayoutContainer.vue'),
      // 重定向到文章管理页面
      redirect: '/article/manage',
      // 二级子路由
      children: [
        { path: '/article/manage', component: () => import('@/views/article/ArticleManage.vue') },
        { path: '/article/channel', component: () => import('@/views/article/ArticleChannel.vue') },
        { path: '/user/profile', component: () => import('@/views/user/UserProfile.vue') },
        { path: '/user/avatar', component: () => import('@/views/user/UserAvatar.vue') },
        { path: '/user/password', component: () => import('@/views/user/UserPassword.vue') }
      ]
    }
    /*{
      path: '/',
      name: 'home',
      component: LoginPage
    },
    {
      path: '/about',
      name: 'about',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/AboutView.vue')
    }*/
  ]
})

// 路由拦截器 - 导航守卫 前置守卫
// 登录访问拦截  =>  默认是直接放行
// 根据返回值决定，是放行还是拦截
// 返回值：直接放行
// 1. undefined / true
// 2. false 拦回from的地址页面
// 3. 具体路径或路径对象拦截到对应的地址
//    '/login' { name: 'login' }
router.beforeEach((to) => {
  // 如果没有token，且访问的是非登录页，拦截到登录，其他情况正常放行
  const useStore = useUserStore()
  if(!useStore.token && to.path !== '/login') return '/login'
  // return true
})

export default router
